package com.heima.user.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.user.AdminConstans;
import com.heima.common.exception.CustomException;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.feign.WemediaFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    protected WemediaFeign wemediaFeign;

    @Autowired
    private ArticleFeign articleFeign;

    @Override
    public ResponseResult findListByStatus(AuthDto dto) {
        //检查参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //封装条件 分页条件 查询条件
        Page<ApUserRealname> pageRequest = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> queryWrapper = Wrappers.lambdaQuery();
        if(dto.getStatus()==null){
            queryWrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        //执行查询
        IPage<ApUserRealname> pageResult = page(pageRequest, queryWrapper);

        //封装接口返回
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), pageRequest.getTotal());
        responseResult.setData(pageResult.getRecords());
        return responseResult;
    }

    /**
     *
     * @param dto status (2 失败，9通过) id msg 失败原因
     * @return
     */
    @GlobalTransactional
    @Override
    public ResponseResult updateByStatus(AuthDto dto) {
        //检查参数
        if(dto==null || dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(!checkStatus(dto.getStatus())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据ID修改 ap_user_realname(apUser apUserRealname功能不实现 需要自己添加数据)表的status
        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(dto.getStatus());
        if(StringUtils.isNotBlank(dto.getMsg())){
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);
        //如果是审核通过的话，需要同步消息到wemedia和article
        if(dto.getStatus()==AdminConstans.PASS_AUTH){
            createWmUserAndAuthor(dto.getId());

        }


        return null;
    }

    private void createWmUserAndAuthor(Integer id) {
        //获取apuser的信息，根据realname表关联的userId来查询
        ApUserRealname apUserRealname = getById(id);
        Integer userId = apUserRealname.getUserId();
        // 通过userRealname中的  姓名 和 身份证号  去公安系统数据库中查询是否真实存在
//        boolean checkIdCard = IdCardUtils.checkIdCardInfo(apUserRealname.getRealName(), apUserRealname.getIdno());
//        if(!checkIdCard){
//            throw new CustomException(ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"实名认证的身份证信息错误"));
//        }
        ApUser apUser = apUserMapper.selectById(userId);
        if(apUser==null){
            throw  new CustomException(ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证失败"));
        }

        //查询自媒体用户是否存在 如果不存在 创建WmUser 保存
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());

        if(wmUser==null){
            wmUser = new WmUser();
            wmUser.setApUserId(userId);
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setImage(apUser.getImage());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setStatus(9);
            wmUser.setType(0);
            wmUser.setCreatedTime(new Date());
            wemediaFeign.save(wmUser);
        }
        createAuthor(wmUser);
        //查询作者信息是否存在 如果不存在 创建ApAuthor 保存



    }

    private void createAuthor(WmUser wmUser) {
        // 查询作者信息是否存在
        ApAuthor apAuthor = articleFeign.findByUserId(wmUser.getApUserId());
        // null代表作者不存在   创建一个作者
        if(apAuthor == null){
            apAuthor = new ApAuthor();
            apAuthor.setName(wmUser.getName());
            apAuthor.setType(2);
            apAuthor.setUserId(wmUser.getApUserId());
            apAuthor.setCreatedTime(new Date());
            apAuthor.setWmUserId(wmUser.getId());
            articleFeign.save(apAuthor);
        }

    }

    /**
     *不能为空 必须是2 或9
     * @param status
     * @return
     */
    public boolean checkStatus(Short status){
        if(status==null || (status!= AdminConstans.FAIL_AUTH &&status!=AdminConstans.PASS_AUTH)){
            return false;
        }
        return true;
    }
}
